package org.jaaksi.androidforflutterdemo

import libcore.config.LogUtil
import okhttp3.ResponseBody
import org.jaaksi.androidforflutterdemo.api.NetworkPluginApi
import org.jaaksi.androidforflutterdemo.server.ApiClient
import org.jaaksi.flutter.network.Callback
import org.jaaksi.flutter.network.NetworkFunction
import retrofit2.Call
import retrofit2.Response

class NetworkFunctionImp : NetworkFunction {
  override fun rawGet(path: String, prams: Map<String, Any>?, callback: Callback<String>) {
    ApiClient.create(NetworkPluginApi::class.java).get(path, prams ?: hashMapOf())
      .enqueue(object : retrofit2.Callback<ResponseBody?> {
        override fun onFailure(call: Call<ResponseBody?>, t: Throwable) {
          callback.call(null)
        }

        override fun onResponse(call: Call<ResponseBody?>, response: Response<ResponseBody?>) {
          try {
            callback.call(response.body()?.string())
          } catch (e: Exception) {
            LogUtil.e("http", e.message)
            callback.call(null)
          }
        }
      })
  }

  override fun rawPost(path: String, prams: Map<String, Any>?, callback: Callback<String>) {
    ApiClient.create(NetworkPluginApi::class.java).post(path, prams ?: hashMapOf())
      .enqueue(object : retrofit2.Callback<ResponseBody?> {
        override fun onFailure(call: Call<ResponseBody?>, t: Throwable) {
          callback.call(null)
        }

        override fun onResponse(call: Call<ResponseBody?>, response: Response<ResponseBody?>) {
          try {
            callback.call(response.body()?.string())
          } catch (e: Exception) {
            LogUtil.e("http", e.message)
            callback.call(null)
          }
        }
      })
  }
}